require 'digest/sha1'

class User < ActiveRecord::Base
	attr_accessible :password, :password_confirmation, :email, :first_name, :middle_name, :last_name, :phone_num, :address, :alt_email, :authority
	
    validates_length_of :email, :within => 3..40
	###########
	# VALIDATION NEEDS TO BE MOVED OUT OF THE MODEL
    # validates_length_of :password, :within => 5..40
    # validates_presence_of :email, :password, :password_confirmation, :salt
    # validates_confirmation_of :password    
	###########
	validates_uniqueness_of :email
    validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :message => "Invalid email"
    attr_protected :id, :salt
  
    attr_accessor :password, :password_confirmation
    
    
    
  belongs_to :group

protected

  def self.random_string(len)
      chars = ("a".."z").to_a + ("a".."Z").to_a + ("0".."9").to_a
      newpass = ""
      1.upto(len) { |i| newpass << chars[rand(chars.size-1)] }
      return newpass
  end

public
  
  def password=(pass)
      @password=pass
      self.salt = User.random_string(10)
      self.hashed_password = User.encrypt(@password, self.salt)
  end

protected

  def self.encrypt(pass, salt)
      Digest::SHA1.hexdigest(pass+salt)
  end

public

  def self.authenticate(email, pass)
      u=find(:first, :conditions=>["email = ?", email])
      return nil if u.nil?
      return u if User.encrypt(pass, u.salt)==u.hashed_password
      nil
  end

  def send_new_password
    new_pass = User.random_string(10)
    self.password = self.password_confirmation = new_pass
    self.save
    Notifications.deliver_forgot_password(self.email, self.login, new_pass)
  end

end
